<template>
  <div>
    <el-row>
      <el-col align="center">
        <H1>{{ schema.displayName }}</H1>
      </el-col>
    </el-row>
    <el-row style="padding:2px;margin-bottom: 2px">
      <el-col align="left" :span="18">
        <el-button
          @click="handleDataAdd()"
          size="mini"
          class="el-button--primary"
          icon="el-icon-plus"
          >增 加
        </el-button>
        <el-button
          @click="handleDataDelete()"
          size="mini"
          class="el-button--primary"
          >删 除
        </el-button>
        <el-button
          @click="handleDataClear()"
          size="mini"
          class="el-button--primary"
          icon="el-icon-plus"
          >清空数据
        </el-button>
      </el-col>
      <el-col align="right" :span="6"
        ><el-button
          @click="handleSchemaEdit()"
          size="mini"
          class="el-button--primary"
          icon="el-icon-back"
          >修改模型
        </el-button></el-col
      >
    </el-row>
    <el-row>
      <el-col>
        <el-table
          size="mini"
          :data="tableData.data"
          border
          style="width: 100%"
          highlight-current-row
        >
          <el-table-column type="index"></el-table-column>
          <el-table-column
            v-for="v in tableData.fields"
            :prop="v.name"
            v-bind:key="v.name"
            :label="v.displayName"
            :width="v.width"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.isSet">
                <el-input
                  size="mini"
                  placeholder="请输入内容"
                  v-model="tableData.sel[v.name]"
                >
                </el-input>
              </span>
              <span v-else>{{ scope.row[v.name] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="el-button--primary"
                @click="handleDataEdit(scope.row, scope.$index)"
                >修改
              </el-button>
              <el-button
                size="mini"
                class="el-button--danger"
                @click="handleDataDelete(scope.row, scope.$index)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <div id="dialogForm">
      <el-dialog title="新建" :visible.sync="dialogFormVisible">
        <el-form :model="oneRecord">
          <el-form-item
            v-for="f in tableData.fields"
            v-bind:key="f.name"
            :label="f.displayName"
            :label-width="formLabelWidth"
          >
            <template>
              <el-input
                v-if="'Password' === f.type"
                v-model="oneRecord[f.name]"
                placeholder="请输入密码"
                show-password
              ></el-input>
              <el-input v-else v-model="oneRecord[f.name]"></el-input>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDataSave"
            >{{ oneRecord.__id ? '更新' : '保存' }}
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import * as schema from '../../api/schema'
import * as data from '../../api/data'
//
// var generateId = {
//   _count: 1,
//   get() {
//     return +new Date() + '_' + this._count++
//   }
// }
export default {
  data() {
    return {
      dialogFormVisible: false,
      dialogFormUpdating: false,
      formLabelWidth: '100px',
      schemaName: null,
      schema: { displayName: '未定义' },
      keyName: '__id',
      oneRecord: {},
      tableData: {
        sel: null, //选中行
        fields: [],
        data: []
      }
    }
  },
  activated() {
    if (this.$route.params.schema) {
      this.schemaName = this.$route.params.schema
      this.loadData()
    } else if (this.$route.query.schema) {
      this.schemaName = this.$route.query.schema
      this.loadData()
    } else {
      this.$message.warning('No schema name provided.')
    }
  },
  methods: {
    async loadData() {
      let result = await schema.FINDONE({
        group: 'default',
        name: this.schemaName
      })
      if (result.code === 0 && result.data) {
        this.schema = result.data
        this.tableData = {
          sel: null, //选中行
          fields: [],
          data: []
        }
        this.tableData.fields = result.data.fields
        let dataResult = await data.FINDALL({ type: this.schemaName })
        if (dataResult.code === 0 && dataResult.data) {
          this.tableData.data = dataResult.data
          this.$message({
            message: '数据加载完成！',
            type: 'success'
          })
        } else {
          this.$message({
            message: '数据加载错误：' + dataResult,
            type: 'warning'
          })
          console.log('loadData error: ' + dataResult)
        }
      } else {
        this.$message({
          message: '数据加载错误：' + result,
          type: 'warning'
        })
        console.log('loadData error: ' + result)
      }
    },
    handleSchemaEdit() {
      this.$router.push({
        name: 'DataDefine',
        params: { name: this.schemaName }
      })
    },
    handleDataAdd() {
      this.oneRecord = {}
      this.dialogFormVisible = true
    },
    async handleDataSave() {
      let saveObject = {
        type: this.schemaName,
        key: this.oneRecord[this.keyName],
        data: this.oneRecord
      }
      let saveResult = await data.SAVEORUPDATE(saveObject)
      if (saveResult.code === 0) {
        this.$message({
          message: '恭喜你，数据保存成功！',
          type: 'success'
        })
        this.dialogFormVisible = false
        this.loadData()
      } else {
        this.$message({
          message: '数据保存失败：' + saveResult,
          type: 'warning'
        })
      }
    },
    async handleDataEdit(row) {
      this.oneRecord = row
      this.dialogFormUpdating = true
      this.dialogFormVisible = true
    },
    handleDataClear() {
      this.$confirm(
        '此操作将永久删除所有"' + this.schemaName + '"数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          let clearResult = await data.CLEAR({ type: this.schemaName })

          if (clearResult.code === 0) {
            this.$message({
              message: '数据已清空！',
              type: 'success'
            })
            this.loadData()
          } else {
            this.$message({
              message: '数据清空失败：' + clearResult,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async handleDataDelete(row) {
      this.$confirm('此操作将永久删除该行数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let delResult = await data.DELETE({
            type: this.schemaName,
            key: row[this.keyName]
          })
          if (delResult.code === 0) {
            this.$message({
              message: '数据已删除！',
              type: 'success'
            })
            this.loadData()
          } else {
            this.$message({
              message: '数据删除失败：' + delResult,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }

    //读取表格数据
    // readMasterUser() {
    //   //根据实际情况，自己改下啊
    //   this.tableData.data.map(i => {
    //     i.id = generateId.get() //模拟后台插入成功后有了id
    //     i.isSet = false //给后台返回数据添加`isSet`标识
    //     return i
    //   })
    // },
    // //添加账号
    // addMasterUser() {
    //   for (let i of this.tableData.data) {
    //     if (i.isSet) return this.$message.warning('请先保存当前编辑项')
    //   }
    //   let j = {
    //     id: 0,
    //     type: '',
    //     addport: '',
    //     user: '',
    //     pwd: '',
    //     info: '',
    //     isSet: true,
    //     _temporary: true
    //   }
    //   this.tableData.data.push(j)
    //   this.tableData.sel = JSON.parse(JSON.stringify(j))
    // },
    //修改
    // pwdChange(row, index, cg) {
    //   //点击修改 判断是否已经保存所有操作
    //   for (let i of this.tableData.data) {
    //     if (i.isSet && i.id != row.id) {
    //       this.$message.warning('请先保存当前编辑项')
    //       return false
    //     }
    //   }
    //   //是否是取消操作
    //   if (!cg) {
    //     if (!this.tableData.sel.id) this.tableData.data.splice(index, 1)
    //     return (row.isSet = !row.isSet)
    //   }
    //   //提交数据
    //   if (row.isSet) {
    //     //项目是模拟请求操作  自己修改下
    //     // ;(function() {
    //     let data = JSON.parse(JSON.stringify(this.tableData.sel))
    //     for (let k in data) row[k] = data[k]
    //     this.$message({
    //       type: 'success',
    //       message: '保存成功!'
    //     })
    //     //然后这边重新读取表格数据
    //     this.readMasterUser()
    //     row.isSet = false
    //     // })()
    //   } else {
    //     this.tableData.sel = JSON.parse(JSON.stringify(row))
    //     row.isSet = true
    //   }
    // }
  }
}
</script>
<style scoped>
h1 {
  align-content: center;
  font-family: Arial, sans-serif;
  font-size: 24px;
  color: #369;
}
/*.el-table-add-row {*/
/*  margin-top: 10px;*/
/*  width: 100%;*/
/*  height: 34px;*/
/*  border: 1px dashed #c1c1cd;*/
/*  border-radius: 3px;*/
/*  cursor: pointer;*/
/*  justify-content: center;*/
/*  display: flex;*/
/*  line-height: 34px;*/
/*}*/
</style>
